/*
 * Copyright (C) 2011 Mette Bank, Rikke Jensen, Kenneth Brodersen, Thomas Pedersen
 * 
 * This file is part of digiPECS.
 * 
 * digiPECS is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * digiPECS is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with digiPECS.  If not, see <http://www.gnu.org/licenses/>.
 */

package sw6.digipecs.admin;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

import sw6.digipecs.R;
import sw6.digipecs.exceptions.DatabaseException;
import sw6.digipecs.exceptions.IDNotFoundException;
import sw6.digipecs.exceptions.ImageIsEmptyException;
import sw6.digipecs.helpers.ToastHelper;
import sw6.digipecs.model.ExtImage;
import sw6.digipecs.model.ExtImageInSituation;
import sw6.digipecs.model.PECSBook;
import sw6.digipecs.model.Situation;
import sw6.digipecs.widget.admin.SelectableExtImageAdapter;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;

public class AddImagesToSituationActivity extends Activity implements OnItemClickListener {
	public static final String SITUATION_ID = "situation_id";
	public static final int REQUEST_CODE = 4;
	private GridView mImageGridView;
	private Context mContext;
	private PECSBook mBook;
	private SelectableExtImageAdapter<ExtImage> mImagesAdapter;
	private ArrayList<ExtImage> mAllImages;
	private ArrayList<ExtImage> mImages;
	private Intent mInvokeIntent;
	private Comparator<Object> mComparer;

	/**
	 * @see android.app.Activity#onCreate(Bundle)
	 */
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.addimagestositutationactivitymainlayout); 
		mInvokeIntent=getIntent(); 
		initialise(); 
	}

	private void initialise() {
		mImageGridView = (GridView) findViewById(R.id.addImagesToSituationGridView);
		mImageGridView.setOnItemClickListener(this) ; 
		mContext=getApplicationContext(); 
		mBook = new PECSBook(mContext,PECSBook.Views.All);
		mBook.open(); 
		mAllImages = mBook.getAllPictures(); 
		mBook.close(); 
		mComparer = new Comparator<Object>(){
            public int compare(Object o1, Object o2) {
                ExtImage s1 = (ExtImage) o1;
                ExtImage s2 = (ExtImage) o2;
                Integer id1=null, id2 = null;
				try {
					id1 = new Integer(s1.getId());
					id2 = new Integer(s2.getId()); 
				} catch (ImageIsEmptyException e) {
					throw new RuntimeException(e);
				}         
               return id1.compareTo(id2);
            }
        };
		LoadGridview();
	}

	private void LoadGridview() {
		//Lets try to sort this puppy!
		Situation situation=null; 
		try {
			situation = new Situation(mContext, (mInvokeIntent.getExtras()).getInt(SITUATION_ID));
			
			Log.i("sw6.admin", "Adding pictures to situation (" + situation.getId() + ")");
			
			// Sort the list containing pictures already in situation
			ArrayList<ExtImageInSituation> situationImages = situation.getAllPictures(mContext);
			Collections.sort(situationImages, mComparer);
			
			Log.i("sw6.admin", situationImages + " pictures currently in situation");
			
			ArrayList<ExtImage> imagesToShow = new ArrayList<ExtImage>();
			for(ExtImage img:mAllImages)
			{
				int pos = Collections.binarySearch(situationImages, img, mComparer);
				if(pos<0) {
					imagesToShow.add(img);
				}
			}
			
			mImages=imagesToShow; 
			mImagesAdapter = new SelectableExtImageAdapter<ExtImage>(mContext,mImages,SelectableExtImageAdapter.SELECT_MODE_ADD); 
			mImageGridView.setAdapter(mImagesAdapter);
			
		} catch (IDNotFoundException e) {
			throw new RuntimeException(e);
		}
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		ExtImage image = mImages.get(arg2); 
		image.setIsSelected(!image.isSelected()); 
		mImages.set(arg2, image); 
		mImagesAdapter.notifyDataSetChanged(); 
		//LoadGridview(); 
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
	    if ((keyCode == KeyEvent.KEYCODE_BACK)) {
	        saveSelectedPictures(); 
	        setResult(RESULT_OK); 
	        finish(); 
	    }
	    return super.onKeyDown(keyCode, event);
	}

	private void saveSelectedPictures() {
		Bundle extras = mInvokeIntent.getExtras(); 
		int situationId = extras.getInt(SITUATION_ID); 
		try {
			Situation situation = new Situation(mContext, situationId);
			for(ExtImage image:mImages)
			{
				if(image.isSelected())
					situation.addPicture(image); 
			}
			
		} catch (IDNotFoundException e) {
			e.printStackTrace();
		} catch (DatabaseException e) {
			ToastHelper.showError(mContext, R.string.errorAddPicDB);
			e.printStackTrace();
		} catch (ImageIsEmptyException e) {
			throw new RuntimeException(e);
		}
	}
}
